package com.tms.warehouse.mappings;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.tms.warehouse.Warehouse;
import com.tms.warehouse.entity.Rack;
import com.tms.warehouse.entity.Series;

public class RackMapper extends AbstractMapper<Rack> {

	// Rack
	static final String ENTITY_NAME = "Rack";
	private static final String PROPERTY_NAME = "name";
	private static final String PROPERTY_NUMBER = "number";
	private static final String PROPERTY_SERIES = "series";

	@Override
	public String getType() {

		return ENTITY_NAME;
	}

	@Override
	public Rack wrap(Entity entity) {

		String name = (String) entity.getProperty(PROPERTY_NAME);
		long number = (Long) entity.getProperty(PROPERTY_NUMBER);
		Key seriesKey = (Key) entity.getProperty(PROPERTY_SERIES);
		Series series = seriesKey == null ? null : Warehouse
				.findSeriesById(String.valueOf(seriesKey.getId()));
		long id = entity.getKey().getId();
		return new Rack(id, name, (int) number, series);
	}

	@Override
	public Entity unwrap(Rack entity) {

		Entity rack;
		if(entity.getId() > 0) {
			rack = new Entity(createKey(entity.getId()));
		} else {
			rack = new Entity(ENTITY_NAME);			
		}
		rack.setProperty(PROPERTY_NAME, entity.getName());
		rack.setProperty(PROPERTY_NUMBER, entity.getNumber());
		rack.setProperty(PROPERTY_SERIES,
				mapRelation(entity.getSeries(), new AbstractMapper<Series>(){}));
		return rack;
	}

}
